package com.gzz.controller;


import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.gzz.common.R;
import com.gzz.pojo.SystemMessage;
import com.gzz.pojo.UserAdvise;
import com.gzz.service.SystemMessageService;
import com.gzz.service.UserAdviseService;
import com.gzz.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static cn.hutool.core.date.DateTime.now;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 */
@RestController
@RequestMapping("/api/system-message")
public class SystemMessageController {
	@Autowired
	SystemMessageService systemMessageService;
	@Autowired
	UserAdviseService userAdviseService;

	private SystemMessage systemMessage;

	@PutMapping("/add")
	public R addMessage(@RequestBody SystemMessage systemMessage)
	{

		UpdateWrapper<UserAdvise> userAdviseUpdateWrapper = new UpdateWrapper<>();
		userAdviseUpdateWrapper.eq("id",systemMessage.getAdviceId());
		userAdviseUpdateWrapper.set("isRead",1);
		userAdviseUpdateWrapper.set("back_context",systemMessage.getContext());
		userAdviseService.update(userAdviseUpdateWrapper);

		systemMessage.setCreateTime(now());
		Long id =(long) Math.abs(UUID.randomUUID().hashCode());
		systemMessage.setId(id);
		systemMessageService.save(systemMessage);
		return R.success(true);
	}
	@PutMapping("/sadd")
	public R addSMessage(@RequestBody SystemMessage systemMessage){
		systemMessage.setCreateTime(now());
		Long id =(long) Math.abs(UUID.randomUUID().hashCode());
		systemMessage.setId(id);
		systemMessageService.save(systemMessage);
		return R.success(true);
	}
	@GetMapping("/listByid")
	public R<List<SystemMessage>> listbyId(HttpServletRequest request){
		String token = request.getHeader("token");
		//获取用户id
		Long id = JWTUtils.parseToken(token);
		LambdaQueryWrapper<SystemMessage> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(SystemMessage::getUserId,id).orderByDesc(SystemMessage::getCreateTime);
		List<SystemMessage> list = systemMessageService.list(lambdaQueryWrapper);

		return R.success(list);
	}

}

